package cn.shengchao.wecom.dubbo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.examstar.rpc.wecom.api.LocalToWeComRequestApi;
import cn.shengchao.examstar.rpc.wecom.dto.ExternalContactUserDto;
import cn.shengchao.examstar.rpc.wecom.dto.WeComCpUserDto;
import cn.shengchao.examstar.rpc.wecom.dto.WeContactMeResultDto;
import cn.shengchao.wecom.event.WeComUserQrcodeCheckEvent;
import cn.shengchao.wecom.event.WeComUserSyncEvent;
import cn.shengchao.wecom.schedule.WeComTlxSync;
import cn.shengchao.wecom.utils.LocalApiProxy;
import cn.shengchao.wecom.utils.WeComExternalContactHelper;
import cn.shengchao.wecom.utils.WeComTlxHelper;
import cn.shengchao.wecom.wxcp.infrastructure.dao.CpUserCustomerDao;
import cn.shengchao.wecom.wxcp.infrastructure.dao.po.CpUserCustomer;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import top.continew.starter.core.exception.BaseException;

import java.util.List;

/**
 * @program: examstarapi
 * @description: 向企微发出操作请求的业务api
 * @author: Xiong weiqiang
 * @create: 2025-04-10 11:45
 */
@DubboService
public class LocalToWeComRequestDubboApi implements LocalToWeComRequestApi {

    @Autowired
    private WeComTlxHelper weComTlxHelper;
    @Autowired
    private LocalApiProxy localApiProxy;
    @Autowired
    private WeComTlxSync weComTlxSync;
    @Autowired
    private WeComExternalContactHelper weComExternalContactHelper;
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    @Autowired
    private CpUserCustomerDao cpUserCustomerDao;
    @Override
    public void syncAllCpUser() {
        WeComUserSyncEvent event=new WeComUserSyncEvent(this);
        eventPublisher.publishEvent(event);
    }

    @Override
    public void syncCpUserInfo(String userId) {
        try {
            WxCpUser wxCpUser=weComTlxHelper.getWeComUserInfo(0,userId);
            if (wxCpUser!=null){
                WeComCpUserDto weComCpUserDto=new WeComCpUserDto();
                BeanUtil.copyProperties(wxCpUser,weComCpUserDto);
                weComCpUserDto.setGenderCode(wxCpUser.getGender()==null?"0":wxCpUser.getGender().getCode());
                weComTlxSync.checkUpdateCpUser(weComCpUserDto);
            }else {
                throw new BaseException("企微请求成员信息失败:userId="+userId);
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void syncFlowerUserList() {
        try {
            List<String> followUserIds=weComExternalContactHelper.listFollowUsers();
            if (CollUtil.isNotEmpty(followUserIds)){
                localApiProxy.syncLocalUserFollows(followUserIds);
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateExternalUserCustomerDetail(String userId, String cursor) {
        try {
            WxCpExternalContactInfo externalUserDetail=weComExternalContactHelper.getExternalUserDetail(userId,cursor);
            System.out.print("客户"+userId+"结果："+JSONUtil.toJsonStr(externalUserDetail));
            if (externalUserDetail!=null){
                ExternalContactUserDto externalContactUserDto=BeanUtil.copyProperties(externalUserDetail.getExternalContact(), ExternalContactUserDto.class);
                localApiProxy.syncExternalUserCustomerDetail(externalContactUserDto);
            }
            if (CollUtil.isNotEmpty(externalUserDetail.getFollowedUsers())){
//                List<String> followUserIds=weComExternalContactHelper.listFollowUsers();
//                localApiProxy.syncLocalUserFollows(followUserIds);
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void fetchCpUserCustomers(String userId) {
        try {
            List<String> customers=weComExternalContactHelper.getExternalUserId(userId);
            if (CollUtil.isNotEmpty(customers)){
                //                cpUserCustomerDao.saveBatch(cpUserCustomers);
                //                localApiProxy.syncLocalUserCustomers(userId,customers);
                cpUserCustomerDao.delete(Wrappers.lambdaQuery(CpUserCustomer.class).eq(CpUserCustomer::getQywxUserId,userId));
                customers.forEach(customer->{
                    CpUserCustomer cpUserCustomer=new CpUserCustomer();
                    cpUserCustomer.setQywxUserId(userId);
                    cpUserCustomer.setExternalUserid(customer);
                    cpUserCustomerDao.insert(cpUserCustomer);
                });

            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }



    @Override
    public WeContactMeResultDto generateSingleUserContactMe(String userId, String state,String remark) {
        try {
            WxCpContactWayInfo.ContactWay contactWay=new WxCpContactWayInfo.ContactWay();
            contactWay.setUsers(CollUtil.newArrayList(userId));
            contactWay.setState(state);
            contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
            contactWay.setType(WxCpContactWayInfo.TYPE.SINGLE);
            contactWay.setRemark(remark);
            WxCpContactWayResult result= weComExternalContactHelper.getContactMe(contactWay);
            if (result.success()){
                WeContactMeResultDto resultDto=new WeContactMeResultDto();
                resultDto.setConfigId(result.getConfigId());
                resultDto.setQrCode(result.getQrCode());
                return resultDto;
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e.getMessage());

        }
        return null;
    }
    @Override
    public void checkNotQrCodes(List<String> userIds) {
        if (CollUtil.isNotEmpty(userIds)){
            eventPublisher.publishEvent(new WeComUserQrcodeCheckEvent(this, userIds));
        }
    }
}